<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/2/002
 * Time: 10:15
 */

namespace Home\Controller;

use Think\Controller;
class ShopController extends Controller
{
    //初始化方法
    protected function _initialize()
    {
        //检测用户是否登陆 并定义全局变量
        if(isset($_SESSION['msg']['id'])){
            define('UID', $_SESSION['msg']['id']);
        } else {
            $this->redirect('/index.php/Home/Login/login');
        }
    }

    //商品列表
    public function getAjaxData() {
        $p = I('p', 1, 'intval');
        $goods = M('Goods');
        $field = ['id', 'goods_sn', 'goods_name', 'price', 'storage', 'goods_description', 'goods_img'];
        $list = $goods->where(['status'=> 0])->field($field)->page($p)->limit(20)->select();
        foreach ($list as $k=>$v) {
            $list[$k]['price'] = fen_to_yuan($v['price']);
        }

        $this->ajaxReturn(V(1, '商品列表', $list? $list:[]));
    }

    //购买商品
    public function buyGoods() {
        $id = I('id', 0, 'intval');
        $num = I('num', 1, 'intval');
        if (!$id) {
            $this->ajaxReturn(V(0, '请传递购买的商品'));
        }

        $goods = M('Goods');
        $info = $goods->where(['id'=>$id, 'status'=>0])->field(true)->find();

        if(!$info) {
            $this->ajaxReturn(V(0, '选择的商品不存在'));
        }

        $register = M('Register');
        //获取用户信息
        $registerInfo = $register->where(['id'=>UID])->find();
        $needMoney = fen_to_yuan($info['price']*$num); //花费金钱

        if($registerInfo['commissions'] < $needMoney) {
            $this->ajaxReturn(V(0, '余额不足'));
        }

        //判断库存
        if($num > $info['storage']) {
            $this->ajaxReturn(V(0, '库存不足'));
        }

        M()->startTrans();
        //以下满足购买条件 扣除用户余额 生成订单  减少库存 生成扣款日志
        $res1 = $register->where(['id'=>UID])->setDec('commissions', $needMoney);  //减少余额

        $res2 = $goods->where(['id'=>$info['id']])->setDec('storage', $num);      //减少库存

        $data['order_sn'] = date('YmdHis', time()) . '' . randNumber();
        $data['goods_id'] = $info['id'];
        $data['user_id'] = UID;
        $data['number'] = $num;
        $data['real_pay_amount'] = $info['price']*$num; //以分为单位
        $data['remark'] = '购买本商品数量'.$num.',共花费'.$needMoney.'元';
        $data['add_time'] = time();
        $res3 = M('Goodsorder')->add($data);   //写入订单

        $log['member_id'] = UID;
        $log['plus_type'] = 1;
        $log['user_money'] = -$info['price']*$num;
        $log['change_time'] = time();
        $log['desc'] ='商品货号'.$info['goods_sn'].'购买商品数量'.$num.',共花费'.$needMoney.'元';
        $log['type'] = 1;
        $res4 = M('Accountlog')->add($log);  //写入日志

        if ($res1 !== false && $res2 !== false && $res3 && $res4) {
            M()->commit();
            $this->ajaxReturn(V(1, '购买成功等待发货'));
        } else {
            M()->commit();
            $this->ajaxReturn(V(0, '程序出错，购买失败'));
        }
    }

    //商品详情
    public function detail() {
        $id = I('goods_id', 0, 'intval');
        $info = M('Goods')->where(['id'=>$id])->find();
        $info['price'] = fen_to_yuan($info['price']);
        $this->assign('info', $info);
        $this->display('detail');
    }

    public function orderList() {
        if(IS_AJAX) {
            $order = M('Goodsorder');
            $p = I('p', 1,'intval');
            $goods = M('Goods');

            $field = ['id','order_sn', 'goods_id', 'real_pay_amount', 'number', 'send_goods', 'add_time'];
            $list = $order->where(['status'=>0, 'user_id'=>UID])->page($p)->limit(10)->field($field)->select();
            foreach ($list as $k=>$v) {
                $info = $goods->where(['id'=>$v['goods_id']])->find();
                $list[$k]['goodsName'] = $info['goods_name'];
                $list[$k]['goods_img'] = $info['goods_img'];
                $list[$k]['price'] = fen_to_yuan($info['price']);
                $list[$k]['real_pay_amount'] = fen_to_yuan($v['real_pay_amount']);
                $list[$k]['is_send'] = $v['send_goods'] == 1 ? '已发货': '未发货';
            }

            $this->ajaxReturn(V(1, '订单列表', $list ? $list : []));
        } else {
            $this->display('orderList');
        }
    }
}